import React, { useState, useEffect } from "react";
import { View, Text, TouchableOpacity } from "react-native";
import { Audio } from "expo-av";
import { FontAwesome } from "@expo/vector-icons";
import styles from "./index.style";

interface AudioPlayerProps {
  audioUri: string;
  duration: number; // 录音时长（秒）
}

const AudioPlayer = ({ audioUri, duration }: AudioPlayerProps) => {
  const [sound, setSound] = useState<Audio.Sound | null>(null);
  const [isPlaying, setIsPlaying] = useState(false);
  const [position, setPosition] = useState(0);
  const [isLoaded, setIsLoaded] = useState(false);

  // 加载音频
  const loadSound = async () => {
    try {
      // 清理之前的音频对象
      if (sound) {
        await sound.unloadAsync();
      }

      // 创建新的音频对象
      const { sound: newSound } = await Audio.Sound.createAsync(
        { uri: audioUri },
        { shouldPlay: false },
        onPlaybackStatusUpdate
      );

      // 设置状态
      setSound(newSound);
      setIsLoaded(true);
    } catch (error) {
      console.error("Error loading sound:", error);
    }
  };

  // 播放状态更新回调
  const onPlaybackStatusUpdate = (status) => {
    if (status.isLoaded) {
      setPosition(status.positionMillis / 1000); // 转换为秒
      setIsPlaying(status.isPlaying);

      // 播放结束时重置
      if (status.didJustFinish) {
        setIsPlaying(false);
        setPosition(0);
        sound?.setPositionAsync(0);
      }
    }
  };

  // 播放/暂停切换
  const togglePlayPause = async () => {
    if (!sound) return;

    if (isPlaying) {
      await sound.pauseAsync();
    } else {
      // 播放前设置音频模式
      await Audio.setAudioModeAsync({
        allowsRecordingIOS: false,
        playsInSilentModeIOS: true,
        staysActiveInBackground: true,
        interruptionModeIOS: 1,
        interruptionModeAndroid: 1,
      });

      await sound.playAsync();
    }
  };

  // 组件加载时初始化音频
  useEffect(() => {
    loadSound();

    // 组件卸载时释放资源
    return () => {
      if (sound) {
        sound.unloadAsync();
      }
    };
  }, [audioUri]);

  // 格式化时间
  const formatTime = (seconds: number) => {
    const mins = Math.floor(seconds / 60);
    const secs = Math.floor(seconds % 60);
    return `${mins.toString().padStart(2, "0")}:${secs
      .toString()
      .padStart(2, "0")}`;
  };

  // 计算进度百分比
  const progressPercent = isNaN(position / duration)
    ? 0
    : (position / duration) * 100;

  return (
    <View style={styles.container}>
      <TouchableOpacity style={styles.playButton} onPress={togglePlayPause}>
        <FontAwesome
          name={isPlaying ? "pause" : "play"}
          size={16}
          color="#1AAD19"
        />
      </TouchableOpacity>

      <View style={styles.progressContainer}>
        <View style={styles.progressTrack}>
          <View
            style={[styles.progressFill, { width: `${progressPercent}%` }]}
          />
        </View>

        <View style={styles.timeContainer}>
          <Text style={styles.currentTime}>{formatTime(position)}</Text>
          <Text style={styles.duration}>{formatTime(duration)}</Text>
        </View>
      </View>
    </View>
  );
};

export default AudioPlayer;
